package fr.cnam.projetSiw.client.core;

import com.google.gwt.core.client.Callback;
import com.google.gwt.core.client.GWT;
import com.google.gwt.geolocation.client.Geolocation;
import com.google.gwt.geolocation.client.Position;
import com.google.gwt.geolocation.client.PositionError;
import com.google.gwt.place.shared.PlaceHistoryHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;

import fr.cnam.projetSiw.client.services.GeolocatorService;
import fr.cnam.projetSiw.client.services.GeolocatorServiceAsync;
import fr.cnam.projetSiw.shared.City;

public class GeolocationManager {
	
	private static GeolocationManager INSTANCE = null;
	private Position position;
	private City city;
	private GeolocatorServiceAsync geoService = GWT.create(GeolocatorService.class);

	
	private GeolocationManager(){
	}
	
	public static GeolocationManager getInstance(){
		if(INSTANCE == null){
			INSTANCE = new GeolocationManager();
		}
		
		return INSTANCE;
	}

	public Position getPosition() {
		return position;
	}

	public void setPosition(Position position) {
		this.position = position;
	}
	
	public void searchCurrentPosition(final PlaceHistoryHandler historyHandler) {
		Geolocation geoLoc = Geolocation.getIfSupported();
		
		geoLoc.getCurrentPosition(new Callback<Position, PositionError>() {
			
			@Override
			public void onSuccess(Position result) {
				setPosition(result);
				geoService.getCity(""+position.getCoordinates().getLongitude(), ""+position.getCoordinates().getLatitude() , new AsyncCallback<City>() {

					@Override
					public void onFailure(Throwable caught) {
						caught.printStackTrace();
					}

					@Override
					public void onSuccess(City result) {
						setCity(result);
						GeoZic.handleHistory(historyHandler);

					}
				});
				
			}
			
			@Override
			public void onFailure(PositionError reason) {
				System.err.println(reason.toString());
			}
		});
		

	}

	public City getCity() {
		return city;
	}

	public void setCity(City city) {
		this.city = city;
	}
}
